"""
@author: haha
@file: api_data.py
@time: 2023/3/10 0010 19:36:58
"""
import http.client, urllib, json
import pymysql

db = pymysql.connect(host="192.168.152.141",
                     user="sctl",
                     password="123456",
                     database="flask")

def in_database(value):

    cursor = db.cursor()
    sql = f"insert into datadb values({value})"
    cursor.execute(sql)
    db.commit()


conn = http.client.HTTPSConnection('apis.tianapi.com')  #接口域名
params = urllib.parse.urlencode({'key':'bb72fb028f56f83edc1adf4c46121723','num':'10'})
headers = {'Content-type':'application/x-www-form-urlencoded'}
conn.request('POST','/auto/index',params,headers)
tianapi = conn.getresponse()
result = tianapi.read()
data = result.decode('utf-8')
dict_data = json.loads(data)
news_list = dict_data.get('result').get('newslist')
print(news_list)
for new in news_list:
    # print(new)
    id = new.get('id')
    ctime = new.get('ctime')
    title = new.get('title')
    description = new.get('description')
    picUrl = new.get("picUrl")
    url = new.get('url')

    value = f"'{id}','{ctime}','{title}','{description}','{picUrl}','{url}'"
    in_database(value)

db.close()
print("保存数据成功")


